package com.neusoft.bd.myflink.step08;

import com.neusoft.bd.myflink.entity.WaterSensor;
import com.neusoft.bd.myflink.myfun.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Objects;

public class KeyedValueStateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 7777)
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, ts) -> element.getTs() * 1000L)
                );
        sensorDS.keyBy(r -> r.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    ValueState<Integer> valueState = null;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        valueState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("valueState", Types.INT));
                    }

                    @Override
                    public void processElement(WaterSensor ws, Context ctx, Collector<String> out) throws Exception {
                        Integer preValue = valueState.value();
                        if (Objects.isNull(preValue)) {
                            preValue = (ws.getVc());
                        }
                        if (Math.abs(preValue - ws.getVc()) > 10) {
                            out.collect("传感器=" + ws.getId() + "==>当前水位值=" + ws.getVc() + ",与上一条水位值=" + preValue + ",相差超过10！！！！");
                        }
                        valueState.update(ws.getVc());
                        out.collect("传感器=" + ws.getId() + "==>当前水位值=" + ws.getVc());
                    }

                    @Override
                    public void close() throws Exception {
                        super.close();
                    }
                }).print();
        env.execute();

    }
}
